package com.campus.help.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.campus.help.entity.School;
import com.campus.help.mapper.SchoolMapper;
import com.campus.help.service.SchoolService;
import com.campus.help.vo.SchoolVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 学校服务实现类
 */
@Slf4j
@Service
public class SchoolServiceImpl extends ServiceImpl<SchoolMapper, School> implements SchoolService {

    @Override
    public List<School> getActiveSchools() {
        return baseMapper.selectActiveSchools();
    }

    @Override
    public List<SchoolVO> getSchoolList() {
        List<School> schools = getActiveSchools();
        return schools.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
    }

    @Override
    public SchoolVO getSchoolById(Long id) {
        School school = getById(id);
        if (school == null) {
            return null;
        }
        return convertToVO(school);
    }

    @Override
    public Page<SchoolVO> getSchoolPageList(int page, int size, Integer status, String keyword, String province, String city) {
        log.info("分页查询学校列表 - page: {}, size: {}, status: {}, keyword: {}, province: {}, city: {}",
                page, size, status, keyword, province, city);

        // 创建分页对象
        Page<School> schoolPage = new Page<>(page, size);

        // 将状态转换为字符串（1-启用=ACTIVE，0-禁用=DISABLED）
        String statusStr = null;
        if (status != null) {
            statusStr = status == 1 ? "ACTIVE" : "DISABLED";
        }

        // 执行分页查询 - Mapper返回的是IPage，需要进行类型转换
        IPage<School> iPage = baseMapper.selectSchoolPage(schoolPage, keyword, province, city, statusStr);

        log.info("查询结果 - 总数: {}, 当前页: {}, 总页数: {}", iPage.getTotal(), iPage.getCurrent(), iPage.getPages());

        // 转换为VO
        Page<SchoolVO> voPage = new Page<>(iPage.getCurrent(), iPage.getSize(), iPage.getTotal());
        List<SchoolVO> voList = iPage.getRecords().stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
        voPage.setRecords(voList);

        return voPage;
    }

    @Override
    public boolean addSchool(School school) {
        try {
            log.info("添加学校: name={}, code={}", school.getName(), school.getCode());
            
            // 设置默认状态为启用
            if (school.getStatus() == null || school.getStatus().isEmpty()) {
                school.setStatus("ACTIVE");
            }
            
            boolean result = save(school);
            
            if (result) {
                log.info("添加学校成功: id={}, name={}", school.getId(), school.getName());
            } else {
                log.error("添加学校失败: name={}", school.getName());
            }
            
            return result;
        } catch (Exception e) {
            log.error("添加学校异常: name={}", school.getName(), e);
            throw new RuntimeException("添加学校失败: " + e.getMessage());
        }
    }

    @Override
    public boolean updateSchool(School school) {
        try {
            log.info("更新学校: id={}, name={}", school.getId(), school.getName());
            
            // 检查学校是否存在
            School existSchool = getById(school.getId());
            if (existSchool == null) {
                log.warn("学校不存在: id={}", school.getId());
                throw new RuntimeException("学校不存在");
            }
            
            boolean result = updateById(school);
            
            if (result) {
                log.info("更新学校成功: id={}, name={}", school.getId(), school.getName());
            } else {
                log.error("更新学校失败: id={}", school.getId());
            }
            
            return result;
        } catch (Exception e) {
            log.error("更新学校异常: id={}", school.getId(), e);
            throw new RuntimeException("更新学校失败: " + e.getMessage());
        }
    }

    @Override
    public boolean deleteSchool(Long id) {
        try {
            log.info("删除学校: id={}", id);
            
            // 检查学校是否存在
            School school = getById(id);
            if (school == null) {
                log.warn("学校不存在: id={}", id);
                throw new RuntimeException("学校不存在");
            }
            
            // 软删除（如果需要硬删除，直接使用 removeById）
            boolean result = removeById(id);
            
            if (result) {
                log.info("删除学校成功: id={}, name={}", id, school.getName());
            } else {
                log.error("删除学校失败: id={}", id);
            }
            
            return result;
        } catch (Exception e) {
            log.error("删除学校异常: id={}", id, e);
            throw new RuntimeException("删除学校失败: " + e.getMessage());
        }
    }

    @Override
    public boolean batchDeleteSchools(List<Long> ids) {
        try {
            log.info("批量删除学校: ids={}", ids);
            
            if (ids == null || ids.isEmpty()) {
                log.warn("批量删除学校失败: ids为空");
                throw new RuntimeException("请选择要删除的学校");
            }
            
            boolean result = removeByIds(ids);
            
            if (result) {
                log.info("批量删除学校成功: count={}", ids.size());
            } else {
                log.error("批量删除学校失败: ids={}", ids);
            }
            
            return result;
        } catch (Exception e) {
            log.error("批量删除学校异常: ids={}", ids, e);
            throw new RuntimeException("批量删除学校失败: " + e.getMessage());
        }
    }

    @Override
    public boolean updateSchoolStatus(Long id, String status) {
        try {
            log.info("更新学校状态: id={}, status={}", id, status);
            
            // 检查学校是否存在
            School school = getById(id);
            if (school == null) {
                log.warn("学校不存在: id={}", id);
                throw new RuntimeException("学校不存在");
            }
            
            // 验证状态值
            if (!"ACTIVE".equals(status) && !"DISABLED".equals(status)) {
                log.warn("无效的状态值: status={}", status);
                throw new RuntimeException("无效的状态值");
            }
            
            school.setStatus(status);
            boolean result = updateById(school);
            
            if (result) {
                log.info("更新学校状态成功: id={}, status={}", id, status);
            } else {
                log.error("更新学校状态失败: id={}", id);
            }
            
            return result;
        } catch (Exception e) {
            log.error("更新学校状态异常: id={}, status={}", id, status, e);
            throw new RuntimeException("更新学校状态失败: " + e.getMessage());
        }
    }

    /**
     * 将School实体转换为SchoolVO
     */
    private SchoolVO convertToVO(School school) {
        SchoolVO vo = new SchoolVO();
        vo.setId(school.getId());
        vo.setSchoolName(school.getName());
        vo.setSchoolCode(school.getCode());
        vo.setAddress(school.getAddress());
        vo.setStatus("ACTIVE".equals(school.getStatus()) ? 1 : 0);
        return vo;
    }
}